<template>
  <div>
    <!--  面包屑导航区-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商家管理</el-breadcrumb-item>
    <el-breadcrumb-item>商家列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!--  卡片视图区-->
  <el-card>
<!--    搜索与添加区域-->

    <el-row :gutter="20">
      <el-col :span="12">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getBusinessList">
          <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="addDialogVisible = true">添加商家</el-button>
      </el-col>
    </el-row>
    <el-table :data="businessList" border stripe>
      <el-table-column label="ID" type="index"></el-table-column>
      <el-table-column label="商家名称" prop="businessName"></el-table-column>
      <el-table-column label="所属人" prop="bossName"></el-table-column>
      <!-- <el-table-column label="密码" prop="password"></el-table-column> -->
      <el-table-column label="联系电话" prop="mobile"></el-table-column>
      <el-table-column label="地址" prop="address"></el-table-column>
      <!-- <el-table-column label="角色" prop="role_name"></el-table-column> -->
      <el-table-column label="状态" prop="status">
        <!-- <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status" @change="businessStatusChange(scope.row)">
          </el-switch>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" width="120px">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>

          <!-- <el-tooltip content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
          </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[1, 2, 4, 5]"
      :page-size="this.queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.total">
    </el-pagination>
  </el-card>

 <!-- 添加商家对话框 -->
  <el-dialog
    title="添加商家"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed">
<!--    内容主体区域-->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="商家名称" prop="businessname">
        <el-input v-model="addForm.businessname"></el-input>
      </el-form-item>
      <el-form-item label="商家密码" prop="password">
        <el-input v-model="addForm.password"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input v-model="addForm.gender"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
    </el-form>
   <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>

  <!--修改商家对话框-->
  <el-dialog
    title="修改商家信息"
    :visible.sync="editDialogVisible"
    width="50%"
  @close="editDialogClosed">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="店铺名称" prop="businessName">
        <el-input v-model="editForm.businessName" disabled></el-input>
      </el-form-item>
      <el-form-item label="所属人" prop="bossName">
        <el-input v-model="editForm.bossName"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="editForm.address"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input v-model="editForm.status"></el-input>
      </el-form-item>
      
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser(editForm)">确 定</el-button>
  </span>
  </el-dialog>
  </div>
</template>

<script>
export default {
    name: 'User',
    data() {
      //手机号的自定义验证规则
      const checkMobile = (rule, value, cb) => {
        //验证手机号的正则表达式
        const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
        if (regMobile.test(value)) {
          //邮箱合法
          return cb();
        }
        cb(new Error('手机号格式错误！'));
      }
      return {
        queryInfo: {
          // query: '',
          pagenum: 1,
          pagesize: 2
        },
        businessList: [],
        total: 0,

        // //控制分配角色对话框显示与隐藏的标志
        // setRoleDialogVisible: false,
        //需要被分配角色的商家信息
        // businessInfo: {},
        //所有角色的数据列表
        // rolesList: [],
        //已选中的角色ID
        // selectedRoleId: '',

        //控制添加商家时弹出框显示与隐藏的标志
        addDialogVisible: false,
        //添加商家的表单数据
        addForm: {
          businessname: '',
          password: '',
          gender: '',
          mobile: ''
        },
        //添加商家时的验证规则对象
        addFormRules: {
          businessname: [
            { required: true, message: '请输入商家名', trigger: 'blur' },
            { min: 3, max: 9, message: '长度应在 3 到 9 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 12, message: '长度应在 6 到 12 个字符', trigger: 'blur' }
          ],
          // email: [
          //   { required: true, message: '请输入邮箱', trigger: 'blur' },
          //   {validator: checkEmail, trigger: 'blur'}
          // ],
          mobile: [
            { required: true, message: '请输入联系方式', trigger: 'blur' },
            {validator: checkMobile, trigger: 'blur'}
          ]
        },

        //控制编辑商家对话框的显示与隐藏
        editDialogVisible: false,
        //编辑商家的表单对象
        editForm: {
        },
        //编辑商家时的验证规则对象
        editFormRules: {
          // email: [
          //   { required: true, message: '请输入邮箱', trigger: 'blur' },
          //   {validator: checkEmail, trigger: 'blur'}
          // ],
          mobile: [
            { required: true, message: '请输入联系方式', trigger: 'blur' },
            {validator: checkMobile, trigger: 'blur'}
          ]
        }
      }
    },
    //生命周期函数
    created() {
      this.getBusinessList();
    },
    methods: {
      // 获取商家列表
      async getBusinessList() {
        this.businessList = [];
        const {data: res} = await this.$http.get('business/list', {params:this.queryInfo});
        console.log(res)
        if (res.status !== 200) {
          return this.$message.error('获取商家列表失败')
        }
        // 将商家状态由0、1改为ture、false
        // res.page.records.forEach((v,i)=>{
        //   if(v.status === 0) {
        //     v.status = true
        //     this.usersList.push(v)
        //   }else {
        //     v.status = false
        //     this.usersList.push(v)
        //   }
        // });
        this.businessList = res.page.records;
        this.total = res.page.total;
      },
      //监听 pagesize 改变事件
      handleSizeChange(newSize) {
        // console.log(newSize);
        this.queryInfo.pagesize = newSize;
        this.getBusinessList();
      },
      //监听 currentPage 改变事件
      handleCurrentChange(newPage) {
        // console.log(newPage);
        this.queryInfo.pagenum = newPage;
        this.getBusinessList();
      },
    //  监听商家状态的改变事件
      async businessStatusChange(businessInfo) {
        console.log(businessInfo)
        const {data: res} = await this.$http.post(`business/status?id=${businessInfo.id}`);
        if (res.status !== 200) {
          businessInfo.mg_state = !businessInfo.mg_state;
          return this.$message.error('商家状态修改失败');
        }
        return this.$message.success('商家状态修改成功')
      },
      //搜索商家
      searchUser() {
        this.getBusinessList();
      },
      //监听添加商家对话框的关闭事件,关闭时重置addForm的内容
      addDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },
      //添加商家
      addUser() {
        this.$refs.addFormRef.validate(async vaild => {
          // console.log(vaild);
          if (!vaild) return;
          const {data: res} = await this.$http.post('business/add', this.addForm);
          // console.log(res);
          if (res.status !== 200) return this.$message.error('添加商家失败');
          this.$message.success('添加商家成功');
          this.addDialogVisible = false;
          this.getBusinessList();
        })
      },
      //监听修改商家对话框的关闭事件,关闭时重置editForm的内容
      editDialogClosed() {
        this.$refs.editFormRef.resetFields();
      },
      //显示修改商家对话框，并根据id显示被修改的商家信息
      async showEditDialog(id) {
        this.editDialogVisible = true;
        const {data: res} = await this.$http.get(`business/getBusinessById/${id}`)
        if (res.status !== 200) return this.$message.error('获取商家信息失败！');
        this.editForm = res.data;
        console.log(this.editForm)
      },
      //提交修改后的商家信息
      editUser(editForm) {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return;
          const {data: res} = await this.$http.post(`business/update`, editForm);
          if (res.status !== 200) return this.$message.error('更新失败');
          this.$message.success('更新成功');
          this.editDialogVisible = false;
          this.getBusinessList();
        })
      },
      //  根据id删除商家
      async removeUser(id) {
        const confirmRes = await this.$confirm('此操作将永久删除该商家, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        //如果确认删除，则confirmRes的返回值为 confirm
        //如果取消删除，则confirmRes的返回值为 cancel
        if (confirmRes === 'cancel') return this.$message.info('已取消删除');
        const {data: res} = await this.$http.post(`business/delete?id=${id}`);
        if (res.status !== 200) return this.$message.error('删除失败');
        this.getBusinessList();
        this.$message.success('删除成功');
      }
    }
  }
</script>

<style>

</style>